from functools import wraps

from django.http import JsonResponse

from utils.jwt000 import decode_jwt


def token_required(function):
    @wraps(function)
    def _wrapped_view(self, request, *args, **kwargs):
        token = self.request.META.get('HTTP_AUTHORIZATION')[7:]
        if token is not None:
            # 在这里编写根据 token 判断用户身份的逻辑
            payload = decode_jwt(token)
            if payload != '令牌已过期' and payload != '令牌无效':
                return function(self, request, *args, **kwargs)
            else:
                return JsonResponse({'error': 'Invalid token'}, status=401)
        else:
            return JsonResponse({'error': 'Token is required'}, status=401)

    return _wrapped_view